package cn.pugle.base.collect;

import java.util.PriorityQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * https://www.baeldung.com/java-delay-queue
 *
 * @author tzp
 * @since 2020/9/17
 */
public class DelayApp implements Comparable<DelayApp> {
    public static class DummyDelay implements Delayed {
        public String data;
        public long expired;//TimeUnit.MILLISECONDS

        public DummyDelay(String data, long howLong) {
            this.data = data;
            this.expired = System.currentTimeMillis() + howLong;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            long diff = expired - System.currentTimeMillis();
            return unit.convert(diff, TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            return Long.compare(this.expired, ((DummyDelay) o).expired);
        }

    }

    public static void main(String[] args) throws InterruptedException {
        PriorityQueue<String> priorityQueue = new PriorityQueue<>();
        priorityQueue.add("a");
        priorityQueue.add("c");
        priorityQueue.add("b");

        for (String a; (a = priorityQueue.poll()) != null; ) {
            System.out.println(a);
        }

        System.out.println("----------");

        MyDelayQueue<DummyDelay> delayQueue = new MyDelayQueue<>();
        delayQueue.put(new DummyDelay("a", 1000));
        delayQueue.put(new DummyDelay("b", 10000));
        delayQueue.put(new DummyDelay("c", 100));
        DummyDelay a;
        while ((a = delayQueue.take()) != null) {
            System.out.println(a.data);
        }
    }

    @Override
    public int compareTo(DelayApp o) {
        return 0;
    }
}
